package com.kuang.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.UUID;

public class UploadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        if(!ServletFileUpload.isMultipartContent(req)){
            System.out.println("进入");
            return;
        }

            String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload");
            File uploadFile = new File(uploadPath);
            if( !uploadFile.exists() ){
                uploadFile.mkdir();
            }

            String tmpPath=this.getServletContext().getRealPath("/WEB-INF/tmp");
            File tmpFile = new File(tmpPath);
            if(!tmpFile.mkdir()){
                tmpFile.mkdir();
            }


            DiskFileItemFactory factory=getDiskFileItemFactory(tmpFile);




            ServletFileUpload upload = getServletFileUpload(factory);
//            upload.setProgressListener(new ProgressListener() {
//                public void update(long pBytesRead, long pContentLength, int pItems) {
//                    System.out.println("总大小："+ pContentLength+"已上传："+pBytesRead);
//                }
//            });
//            upload.setHeaderEncoding("utf-8");
//            upload.setFileSizeMax(1024 * 1024 * 10);
//            upload.setFileSizeMax(1024 * 1024 * 10);


        try {

            String msg = uploadParseRequest(upload,req,uploadPath);
//            List<FileItem> fileItems=upload.parseRequest(req);
//
//            for (FileItem fileItem: fileItems) {
//                if(fileItem.isFormField()){
//                    String  name = fileItem.getFieldName();
//                    String value = fileItem.getString("UTF-8");
//                    System.out.println(name + ":" + value);
//                }else{
//                    String uploadFileName=fileItem.getName();
//                    if(uploadFileName.trim().equals("") || uploadFileName == null){
//                        continue;
//                    }
//                    String fileName=uploadFileName.substring(uploadFileName.lastIndexOf("/")+1);
//                    String fileExtName=uploadFileName.substring(uploadFileName.lastIndexOf(".")+1);
//
//                    String uuidPath=UUID.randomUUID().toString();
//
//                    String realPath=uploadPath +"/"+ uuidPath;
//                    File realPathFile = new File(realPath);
//                    if( !realPathFile.exists()){
//                        realPathFile.mkdir();
//                    }
//
//                    InputStream inputStream =fileItem.getInputStream();
//
//                    FileOutputStream fos=new FileOutputStream(realPath+"/"+fileName);
//                    byte[] buffer = new byte[1024* 1024];
//                    int len = 0;
//                    while((len=inputStream.read(buffer))>0){
//                        fos.write(buffer,0,len);
//                    }
//                    fos.close();
//                    inputStream.close();
//
//                    fileItem.delete();
//
//                }
//
//
//            }






        } catch (FileUploadException e) {
            e.printStackTrace();
        }
    }

    public static DiskFileItemFactory getDiskFileItemFactory(File file){
        DiskFileItemFactory factory=new DiskFileItemFactory();
        factory.setSizeThreshold(1024 * 1024);
        factory.setRepository(file);
        return factory;
    }

    public static ServletFileUpload getServletFileUpload(DiskFileItemFactory factory){
        ServletFileUpload upload=new ServletFileUpload(factory);
        upload.setProgressListener(new ProgressListener() {
                public void update(long pBytesRead, long pContentLength, int pItems) {
                    System.out.println("总大小："+ pContentLength+"已上传："+pBytesRead);
                }
            });
            upload.setHeaderEncoding("utf-8");
            upload.setFileSizeMax(1024 * 1024 * 10);
            upload.setFileSizeMax(1024 * 1024 * 10);
            return upload;
    }

    public static String uploadParseRequest(ServletFileUpload upload,HttpServletRequest req,String uploadPath) throws FileUploadException, IOException {
        List<FileItem> fileItems=upload.parseRequest(req);
        String msg = "上传失败";
        for (FileItem fileItem: fileItems) {
            if(fileItem.isFormField()){
                String  name = fileItem.getFieldName();
                String value = fileItem.getString("UTF-8");
                System.out.println(name + ":" + value);
            }else{
                String uploadFileName=fileItem.getName();
                if(uploadFileName.trim().equals("") || uploadFileName == null){
                    continue;
                }
                String fileName=uploadFileName.substring(uploadFileName.lastIndexOf("/")+1);
                String fileExtName=uploadFileName.substring(uploadFileName.lastIndexOf(".")+1);

                String uuidPath=UUID.randomUUID().toString();

                String realPath=uploadPath +"/"+ uuidPath;
                File realPathFile = new File(realPath);
                if( !realPathFile.exists()){
                    realPathFile.mkdir();
                }

                InputStream inputStream =fileItem.getInputStream();

                FileOutputStream fos=new FileOutputStream(realPath+"/"+fileName);
                byte[] buffer = new byte[1024* 1024];
                int len = 0;
                while((len=inputStream.read(buffer))>0){
                    fos.write(buffer,0,len);
                }
                fos.close();
                inputStream.close();
                msg = "上传成功";
                fileItem.delete();

            }

        }

        return msg;
    };
}
